package com.ledi.guns.modular.ledipay.controller;

import io.swagger.annotations.Api;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.plugins.Page;
import com.ledi.guns.common.annotion.Permission;
import com.ledi.guns.common.exception.AppCheckException;
import com.ledi.guns.common.persistence.model.WorkOrderInfo;
import com.ledi.guns.common.persistence.model.vo.TaskRecordVo;
import com.ledi.guns.common.persistence.model.vo.WorkOrderInfoVo;
import com.ledi.guns.core.base.controller.BaseController;
import com.ledi.guns.core.base.tips.SuccessTip;
import com.ledi.guns.core.base.tips.Tip;
import com.ledi.guns.modular.ledipay.controller.req.workOrder.AddWorkOrder;
import com.ledi.guns.modular.ledipay.controller.req.workOrder.DownloadCertificate;
import com.ledi.guns.modular.ledipay.controller.req.workOrder.GetTrackWorkOrder;
import com.ledi.guns.modular.ledipay.controller.req.workOrder.HandleWorkOrder;
import com.ledi.guns.modular.ledipay.controller.req.workOrder.QueryWorkOrder;
import com.ledi.guns.modular.ledipay.controller.req.workOrder.TrackWorkOrder;
import com.ledi.guns.modular.ledipay.service.impl.WorkOrderServiceImpl;

@Api
@RestController
@RequestMapping("/workOrder")
public class WorkOrder extends BaseController {

	@Autowired
	private WorkOrderServiceImpl workOrderService;

	@Value("${cos.file.root.url}")
	private String myqcloudUrl;

	/**
	 * @api {POST} /workOrder/add 工单增加
	 * @apiGroup workOrder
	 * @apiName add
	 * @apiParam {String} schoolName 学校名称
	 * @apiParam {String} phone 手机号码
	 * @apiParam {String} createrName 姓名
	 * @apiVersion 1.0.0
	 * @apiParamExample {json} Request-Example:
	 *                  {
	 *                  "schoolName": "小红幼儿园",
	 *                  "phone":"16548512564",
	 *                  "createrName":"李四"
	 *                  }
	 * @apiSuccessExample {json} Success-Response:
	 *                    {
	 *                    "code": 200,
	 *                    "message": "成功"
	 *                    }
	 */
	@Permission
	@RequestMapping(value = "add", method = RequestMethod.POST)
	public Tip add(@RequestBody AddWorkOrder addAgentInfo) {

		workOrderService.addWorkOrderInfo(addAgentInfo);
		return SuccessTip.buildSuccess();

	}

	/**
	 * @api {POST} /workOrder/list 工单列表
	 * @apiGroup workOrder
	 * @apiName list
	 * @apiParam {String} belongAgentName 所属代理商名称
	 * @apiParam {String} schoolName 学校名称
	 * @apiParam {String} status 状态名称,状态：1-未处理；2处理中；3已处理
	 * @apiSuccess {Long} id 主键ID
	 * @apiSuccess {Long} schoolNature 学校性质（1公立学校，2私立学校）
	 * @apiSuccess {String} alipayPayName 支付宝
	 * @apiSuccess {String} contactTel 手机号
	 * @apiSuccess {String} mailBox 邮箱
	 * @apiSuccess {String} schoolContactPeople 联系人
	 * @apiSuccess {String} statusName 操作状态
	 * @apiSuccess {String} weixinPayName 微信
	 * @apiSuccess {String} schoolName 学校名称
	 * @apiSuccess {Date} createTime 创建时间
	 * @apiSuccess {int} versionNo 版本号
	 * @apiVersion 1.2.0
	 * @apiSuccessExample {json} Success-Response:
	 *                    {
	 *                    "code": 200,
	 *                    "data": {
	 *                    "count": 1,
	 *                    "firstResult": 0,
	 *                    "list": [
	 *                    {
	 *                    "alipayPayName": "需要开通",
	 *                    "belongAgentName": "金华代理商",
	 *                    "contactTel": "",
	 *                    "createTime": "2017-12-03 15:01:05",
	 *                    "id": "3",
	 *                    "mailBox": "",
	 *                    "schoolContactPeople": "",
	 *                    "schoolName": "红黄蓝幼儿园",
	 *                    "statusName": "",
	 *                    "weixinPayName": "需要开通"
	 *                    }
	 *                    ],
	 *                    "orderBy": "id",
	 *                    "orderType": "DESC",
	 *                    "pageNo": 1,
	 *                    "pageSize": 10,
	 *                    "search": {
	 *                    "orderType": "DESC",
	 *                    "defaultPageSize": 10,
	 *                    "pageNo": 1,
	 *                    "belongAgentName": "",
	 *                    "statusName": "",
	 *                    "pageSize": 10,
	 *                    "orderBy": "id",
	 *                    "firstResult": 0,
	 *                    "schoolName": ""
	 *                    },
	 *                    "total": 1
	 *                    },
	 *                    "message": "成功"
	 *                    }
	 */
	@Permission
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public Tip list(@RequestBody QueryWorkOrder queryWorkOrder) {

		queryWorkOrder.checkOrder(WorkOrderInfoVo.class);
		Page<WorkOrderInfoVo> page = workOrderService.getWorkOrderInfo(new Page<WorkOrderInfoVo>(queryWorkOrder.getPageNo(), queryWorkOrder.getPageSize()), queryWorkOrder);
		return SuccessTip.buildSuccess(page);
	}

	/**
	 * @api {POST} /workOrder/handle 工单处理
	 * @apiGroup workOrder
	 * @apiName handle
	 * @apiParam {Long} id 工单ID
	 * @apiParam {int} versionNo 版本号
	 * @apiParam {int} type 1:处理工单 2:关闭工单 3:激活工单
	 * @apiVersion 1.0.0
	 * @apiParamExample {json} Request-Example:
	 *                  {
	 *                  "id": 1,
	 *                  "versionNo":2,
	 *                  "type":1
	 *                  }
	 * @apiSuccessExample {json} Success-Response:
	 *                    {
	 *                    "code": 200,
	 *                    "message": "成功"
	 *                    }
	 */
	@Permission
	@RequestMapping(value = "handle", method = RequestMethod.POST)
	public Tip handle(@RequestBody HandleWorkOrder handleWorkOrder) {

		workOrderService.handleWorkOrder(handleWorkOrder);
		return SuccessTip.buildSuccess();
	}

	/**
	 * @api {POST} /workOrder/addTrackRecord 工单增加跟踪记录
	 * @apiGroup workOrder
	 * @apiName addTrackRecord
	 * @apiParam {Long} taskId 工单ID
	 * @apiParam {String} content 跟踪内容
	 * @apiVersion 1.0.0
	 * @apiParamExample {json} Request-Example:
	 *                  {
	 *                  "taskId": 1,
	 *                  "content":"已经跟踪",
	 *                  }
	 * @apiSuccessExample {json} Success-Response:
	 *                    {
	 *                    "code": 200,
	 *                    "message": "成功"
	 *                    }
	 */
	@Permission
	@RequestMapping(value = "addTrackRecord", method = RequestMethod.POST)
	public Tip addTrackRecord(@RequestBody @Valid TrackWorkOrder trackWorkOrder) {

		workOrderService.trackWorkOrders(trackWorkOrder);
		return SuccessTip.buildSuccess();
	}

	/**
	 * @api {POST} /workOrder/getTrackRecord 工单获取跟踪内容
	 * @apiGroup workOrder
	 * @apiName getTrackRecord
	 * @apiParam {Long} id 工单ID
	 * @apiVersion 1.0.0
	 * @apiParamExample {json} Request-Example:
	 *                  {
	 *                  "id": 1
	 *                  }
	 * @apiSuccessExample {json} Success-Response:
	 *                    {
	 *                    "code": 200,
	 *                    "message": "成功"
	 *                    }
	 */
	@Permission
	@RequestMapping(value = "getTrackRecord", method = RequestMethod.POST)
	public Tip getTrackRecord(@RequestBody GetTrackWorkOrder getTrackWorkOrder) {

		List<TaskRecordVo> taskRecordVos = workOrderService.getTaskRecord(getTrackWorkOrder);
		return SuccessTip.buildSuccess(taskRecordVos);
	}

	/**
	 * @api {GET} /workOrder/getSchoolInfo/{id} 查看学校信息
	 * @apiGroup workOrder
	 * @apiName getSchoolInfo
	 * @apiParam id 工单ID
	 * @apiSuccess id 工单ID
	 * @apiSuccess agentId 代理商ID
	 * @apiSuccess schoolName 学校名称
	 * @apiSuccess status 状态：0-未处理；1处理中；2已处理
	 * @apiSuccess isAlipayPay （1：开通支付宝支付，2：不开通支付宝支付）
	 * @apiSuccess isWeixinPay （1：开通微信，2：不开通微信支付）
	 * @apiSuccess schoolContactPeople 学校联系人
	 * @apiSuccess contactTel 联系人手机号
	 * @apiSuccess mailBox 学校对公邮箱
	 * @apiSuccess alipayNumber 学校对公支付宝账号
	 * @apiSuccess photoOrganizeFrameworkUrl 组织结构代码证书或者三证合一证书
	 * @apiSuccess photoPermitUrl 公立学校《事业单位法人证书》私立学校《办学许可证》
	 * @apiSuccess photoOpenAccountUrl 开户许可证
	 * @apiSuccess photoIdPositiveUrl 身份证正面
	 * @apiSuccess photoIdOppositeUrl 身份证反面
	 * @apiVersion 1.0.2
	 * @apiSuccessExample {json} Success-Response:
	 *                    {
	 *                    "code": 200,
	 *                    "data": {
	 *                    "agentId": 17,
	 *                    "alipayNumber": "1541864",
	 *                    "contactTel": "16485223548",
	 *                    "createTime": "2017-12-03 15:01:05",
	 *                    "id": 3,
	 *                    "isAlipayPay": 1,
	 *                    "isDelete": 0,
	 *                    "isWeixinPay": 1,
	 *                    "mailBox": "15684131@163.com",
	 *                    "photoIdOppositeUrl": "",
	 *                    "photoIdPositiveUrl": "",
	 *                    "photoOpenAccountUrl": "",
	 *                    "photoOrganizeFrameworkUrl": "",
	 *                    "photoPermitUrl": "",
	 *                    "schoolContactPeople": "张三",
	 *                    "schoolName": "红黄蓝幼儿园",
	 *                    "status": 2,
	 *                    "updateTime": "2018-03-08 15:58:03",
	 *                    "versionNo": 7
	 *                    },
	 *                    "message": "成功"
	 *                    }
	 */
	@Permission
	@RequestMapping(value = "getSchoolInfo/{id}", method = RequestMethod.GET)
	public Tip getSchoolInfo(@PathVariable Long id) {

		WorkOrderInfo taskRecordVos = workOrderService.getSchoolInfo(id);
		return SuccessTip.buildSuccess(taskRecordVos);
	}

	/**
	 * @api {POST} /workOrder/downloadCertificate 下载证书
	 * @apiGroup workOrder
	 * @apiName downloadCertificate
	 * @apiParam url 下载链接
	 * @apiVersion 1.0.2
	 * @apiSuccessExample {json} error-Response:
	 *                    {
	 *                    "code": 40005,
	 *                    "message": "失败"
	 *                    }
	 */
	@Permission
	@RequestMapping(value = "downloadCertificate", method = RequestMethod.POST)
	public void downloadCertificate(@RequestBody DownloadCertificate downloadCertificate, HttpServletRequest request,
			HttpServletResponse response) {

		URL url;
		OutputStream ouputStream = null;
		InputStream inStream = null;
		String filename;
		try {
			url = new URL(myqcloudUrl + downloadCertificate.getUrl());

			filename = (myqcloudUrl + downloadCertificate.getUrl())
					.substring((myqcloudUrl + downloadCertificate.getUrl()).lastIndexOf("/") + 1);
			filename = URLEncoder.encode(filename, "UTF-8");
			URLConnection conn = url.openConnection();
			inStream = conn.getInputStream();
			ouputStream = response.getOutputStream();

			response.setCharacterEncoding("utf-8");
			response.setContentType("multipart/form-data");
			response.setHeader("Content-disposition", "attachment;filename=" + filename);

			byte[] buffer = new byte[1204];
			int length;
			while ((length = inStream.read(buffer)) != -1) {
				ouputStream.write(buffer, 0, length);
			}
		} catch (Exception e) {
			throw new AppCheckException("school.zhangdan.download.code", "school.zhangdan.download.message");
		} finally {
			try {
				ouputStream.flush();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					ouputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
